import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  baseURL: '', // 使用相对路径，已配置代理
  timeout: 60000, // 请求超时时间
});

// 请求拦截器，添加token到请求头
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('username');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 登录接口
export const login = (username: string, password: string) => {
  return apiClient.post('/api/user/login', { username, password });
};

// 检查登录状态
export const checkLoginStatus = () => {
  return apiClient.get('/api/user/status');
};

// 处理视频接口
export const processVideo = (file: File) => {
  const formData = new FormData();
  formData.append('video', file);
  return apiClient.post('/api/video/process', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    timeout: 600000, // 10分钟超时时间
    onUploadProgress: (progressEvent: any) => {
      if (progressEvent.total) {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log('上传进度:', percentCompleted);
      }
    },
  });
};

// 生成网页特效接口
export const generateWebEffects = (count: number) => {
  return apiClient.get(`/api/effects/web?count=${count}`);
};

// 生成视频特效接口
export const generateVideoEffects = (count: number) => {
  return apiClient.get(`/api/effects/video?count=${count}`);
};

// 下载特效为ZIP文件
export const downloadEffectsAsZip = (urls: string[], type: string) => {
  return apiClient.post('/api/effects/download', { urls, type });
};

export default apiClient; 